//
//  OfficeLeaveViewController.swift
//  EduManage
//
//  Created by design02 on 16/12/12.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class OfficeLeaveViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {

    var segmentedControl = UISegmentedControl()
    var tableView = UITableView()
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    var modetype: String!
    var chart = PDChart()
    var switchBtn = UISwitch()
    var switchSegment = UISegmentedControl()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "请假管理"
        
        setupViews()
    }
    
    func setupViews(){
        
        let array = ["发布数量","按用户"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 15, y: 74, width: screenW - 30, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setupRefresh()
        
    }
    func setupRefresh() {
        if mark == "1" {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeLeaveViewController.refresh))

            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }else {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeLeaveViewController.refresh))
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }
        
    }
    
    /**
     刷新数据
     */
    func refresh() {
        
        if (reachability?.isReachable())! {
            
            let user = getUserPojo()
            let url = server + adminofficewebappapi
            
            if mark == "1" {
                /**
                 1）请假发布数量接口地址：GJ_ModularmentBG.ashx?t=8
                 2）请假发布数量参数：
                 XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
                 */
                
                let request = requestHeader + "8</t><schid>" + user.schid + "</schid></channel></rss>"
                
                workArray = getData(url, request: request)
                
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
                
                setupSwitchBtn()
                
                if switchSegment.selectedSegmentIndex == 0 {
                    
                    self.chart.removeFromSuperview()
                    
                    if !self.tableView.subviews.contains(chart) {
                        
                        let barChart: PDBarChart = self.getBarChart(workArray)
                        chart = barChart
                        self.tableView.addSubview(chart)
                    }
                    
                    chart.strokeChart()
                    
                    print("显示柱状图")
                }else if switchSegment.selectedSegmentIndex == 1{
                    
                    self.chart.removeFromSuperview()
                    
                    if !self.tableView.subviews.contains(chart) {
                        
                        let barChart: PDLineChart = self.getLineChart(workArray)
                        chart = barChart
                        self.tableView.addSubview(chart)
                    }
                    
                    chart.strokeChart()
                    
                    print("显示折线图")
                    
                }
                
                
            }else if mark == "2" {
                
                UIView.animate(withDuration: 1.0, animations: {
                    self.chart.removeFromSuperview()
                    self.switchSegment.removeFromSuperview()
                })
                
                /**
                 - 请假（按用户）接口地址：GJ_ModularmentBG.ashx?t=9
                 - 请假（按用户）参数：
                 
                 XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
                 XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
                 XmlNode pageindexxml = ndoc.SelectSingleNode("//rss/channel/pageindex");
                 */
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "9</t><schid>" + user.schid + "</schid><top>6</top><pageindex>" + page + "</pageindex></channel></rss>"
                
                classArray = getData(url, request: request)
                if classArray.count == 0 {
                    TSMessage.showNotification(in: self, title: "温馨提示", subtitle: "暂时还没有请假信息、请添加后重试！", image: nil, type: TSMessageNotificationType.warning, duration: 2.0, callback: nil, buttonTitle: "知道了", buttonCallback: nil, at: TSMessageNotificationPosition.top, canBeDismissedByUser: true)
                }
                
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }
            tableView.reloadData()
            
        } else {
            let alert = UIAlertView.init(title: "错误提示", message: "似乎已断开与互联网的连接", delegate: nil, cancelButtonTitle: "知道了")
            alert.show()
            self.perform(#selector(OfficeLeaveViewController.dimissAlert(alert:)), with: alert, afterDelay: 2.0)
            
            HYLog("网络连接：不可用")
        }
        
        
        tableView.header.endRefreshing()
    }
    func dimissAlert(alert: UIAlertView) {
        alert.dismiss(withClickedButtonIndex: alert.cancelButtonIndex, animated: true)
    }
    
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            setupRefresh()
            break
        case 1:
            mark = "2"
            setupRefresh()
            break
        default:
            break
        }
    }
    
    //MARK: - ui table view delagate and data source 
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            
            return 60
        }else if mark == "2" {
            return 60
        }else {
            return 60
        }
    }
    
    //行数
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if mark == "1" {
            return 0
        }else {
            return classArray.count
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "1" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: ClassSendTableViewCell = ClassSendTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < workArray.count {
                
//                let dic = workArray[indexPath.row] as! JSON
//                let mMonth = dic["mMonth"].stringValue
//                let csnum = dic["csnum"].stringValue
//                let yf = dic["yf"].stringValue
//                let StartDate = dic["StartDate"].stringValue
//                let EndDate = dic["time2"].stringValue

//                cell.textLabel?.text = "\(mMonth)月份、\(csnum)请假、\(yf)排名、\(StartDate.components(separatedBy: " ").first!)-\(EndDate.components(separatedBy: " ").first!)、"
                
            }
            
            return cell
            
        }else if mark == "2" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: OfficeLeaveTableViewCell = OfficeLeaveTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
            
            if (indexPath as NSIndexPath).row < classArray.count {
                
                let dic = classArray[indexPath.row] as! JSON
                
                let longtime = dic["longtime"].stringValue
                let csnum = dic["csnum"].stringValue
                let name = dic["name"].stringValue
                let sl = dic["sl"].stringValue
                
                print("排名、姓名：\(name)、\(sl)次、\(longtime)请假时长")

                var photo = dic["photo"].stringValue
                
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                cell.userName.text = name
                cell.countLabel.text = "请假次数: \(csnum)  "

            }
            
            return cell
            
        }else {
            let cellIdentifier = "GradeSendTableViewCellIdentifier";
            
            let cell: UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            
            return cell
            
        }
        
    }

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("跳转请假详情")
        if mark == "2" {
            let dic = classArray[indexPath.row] as! JSON
            let qjlist = dic["qjlist"].arrayValue
            let name = dic["name"].stringValue
            
            let leaverListVC = OfficeLeaveListVC()
            leaverListVC.leaverArray = qjlist
            leaverListVC.navTitle = name
            self.navigationController?.pushViewController(leaverListVC, animated: true)
        }
        
        
    }
    
    
    //MARK: - 设计图表 - 柱状图
    
    func getBarChart(_ array: NSMutableArray) -> PDBarChart {
        
        
        let tempArr = NSMutableArray()
        var tempPointArr: [CGPoint]?
        var tempMouthArr: [String]?
        
        tempPointArr = [CGPoint]()
        tempMouthArr = [String]()
        
        for i in 0...array.count-1 {
            let tempNumber = (array[i] as! JSON)["csnum"].intValue
            let temgmMonth = (array[i] as! JSON)["mMonth"].intValue
            let tempPoint:CGPoint = CGPoint(x: (array[i] as! JSON)["mMonth"].intValue, y: (array[i] as! JSON)["csnum"].intValue)
            
            tempArr.add(tempNumber)
            tempPointArr?.append(tempPoint)
            tempMouthArr?.append("\(temgmMonth)月")
            
        }

        let m = tempArr.value(forKeyPath: "@max.intValue")! as! Int
        var ymax = CGFloat(0.0)
        var yinterval = CGFloat(0.0)
        
        if (m < 10) {
            ymax = CGFloat(10.0)
            yinterval = 1.0
            
        }else if (m > 10 && m < 100) {
            ymax = CGFloat((m/10+1)*10)
            yinterval = 10.0
            
        }else if (m > 100 && m < 1000) {
            ymax = CGFloat((m/100+1)*10)
            yinterval = 100.0
            
        }else {
            ymax = CGFloat((m/1000+1)*10)
            yinterval = 1000.0
        }
        
        
        let dataItem: PDBarChartDataItem = PDBarChartDataItem()
        dataItem.xMax = CGFloat((tempMouthArr?.count)!)
        dataItem.xInterval = 1.0
        dataItem.yMax = ymax
        dataItem.yInterval = yinterval
        dataItem.barPointArray = tempPointArr
        dataItem.xAxesDegreeTexts = tempMouthArr
        
        dataItem.yAxesDegreeTexts = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        let frameW = self.view.frame.size.width
        let barChart: PDBarChart = PDBarChart(frame: CGRect(x: 15, y: 50, width: frameW-30, height: frameW*3.2/4), dataItem: dataItem)
        return barChart
    }
    
    //MARK: - 折线图
    func getLineChart(_ array: NSMutableArray) -> PDLineChart {
        
        let tempArr = NSMutableArray()
        var tempPointArr: [CGPoint]?
        var tempMouthArr: [String]?
        
        tempPointArr = [CGPoint]()
        tempMouthArr = [String]()
        
        for i in 0...array.count-1 {
            let tempNumber = (array[i] as! JSON)["csnum"].intValue
            let temgmMonth = (array[i] as! JSON)["mMonth"].intValue
            let tempPoint:CGPoint = CGPoint(x: (array[i] as! JSON)["mMonth"].intValue, y: (array[i] as! JSON)["csnum"].intValue)
            
            tempArr.add(tempNumber)
            tempPointArr?.append(tempPoint)
            tempMouthArr?.append("\(temgmMonth)月")
            
        }
        
        
        let m = tempArr.value(forKeyPath: "@max.intValue")! as! Int
        var ymax = CGFloat(0.0)
        var yinterval = CGFloat(0.0)
        
        if (m < 10) {
            ymax = CGFloat(10.0)
            yinterval = 1.0
            
        }else if (m > 10 && m < 100) {
            ymax = CGFloat((m/10+1)*10)
            yinterval = 10.0
            
        }else if (m > 100 && m < 1000) {
            ymax = CGFloat((m/100+1)*10)
            yinterval = 100.0
            
        }else {
            ymax = CGFloat((m/1000+1)*10)
            yinterval = 1000.0
        }
        
        let dataItem: PDLineChartDataItem = PDLineChartDataItem()
        dataItem.xMax = CGFloat((tempMouthArr?.count)!)
        dataItem.xInterval = 1.0
        dataItem.yMax = ymax
        dataItem.yInterval = yinterval
        
        dataItem.pointArray = tempPointArr
        dataItem.xAxesDegreeTexts = tempMouthArr
//        dataItem.yAxesDegreeTexts = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]

        
        let frameW = self.view.frame.size.width
        let lineChart: PDLineChart = PDLineChart(frame: CGRect(x: 15, y: 50, width: frameW-30, height: frameW*3.2/4), dataItem: dataItem)
        return lineChart
    }

    func setupSwitchBtn() {
        
        if !self.tableView.subviews.contains(switchSegment) {
            
            switchSegment = UISegmentedControl.init(items: ["柱状图","折线图"])
            switchSegment.frame = CGRect(x: (screenW-150)/2, y: 5, width: 150, height: 30)
            switchSegment.selectedSegmentIndex = 0
            switchSegment.tintColor = UIColor.init(hexString: "#666666", alpha: 1.0)
            switchSegment.addTarget(self, action: #selector(OfficeLeaveViewController.refresh), for: UIControlEvents.valueChanged)
            self.tableView.addSubview(switchSegment)
        }
        
    }

    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
